package edu.uclm.esi.tysweb.ajedrez.actions;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.SQLException;

import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.struts2.json.JSONException;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import com.gargoylesoftware.htmlunit.javascript.background.DefaultJavaScriptExecutor;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

import edu.uclm.esi.tysweb.ajedrez.dominio.GestorAjedrez;
import edu.uclm.esi.tysweb.ajedrez.dominio.Jugador;
import edu.uclm.esi.tysweb.ajedrez.exceptions.UserAlreadyExistingException;
import edu.uclm.esi.tysweb.ajedrez.utils.ValidatorUtil;

public class RegistrarConCaptchaExterno extends ActionSupport {
	private String email;
	private String pwd1, pwd2;
	private String textoCaptcha, idSession;
	private Exception exception;
	
	public String execute() {
		try {
			if (textoCaptcha==null || idSession==null)
				throw new Exception("Error, te pasaste de listo");
			HttpClient client=new DefaultHttpClient();
			String url="http://alarcosj.esi.uclm.es/ServidorDeCaptchas/getTrue.jsp";
			String pars="textoCaptcha=" + this.textoCaptcha + "&idSession=" + this.idSession;
			HttpPost post=new HttpPost(url + "?" + pars);
			HttpResponse response=client.execute(post);
			InputStream inputStream=response.getEntity().getContent();
			if (inputStream==null)
				throw new Exception("No podemos validar tu petición en este momento");
			JSONObject jso=getJSONObject(inputStream);
			if (!jso.get("result").equals("true"))
				throw new Exception("El captcha no coincide");
			
			GestorAjedrez gestor=GestorAjedrez.get();
			gestor.registrar(email, pwd1);
			this.exception=null;
			return SUCCESS;
		} catch (Exception e) {
			ActionContext.getContext().getSession().put("exception", e);
			this.exception=e;
			return ERROR;
		}
	}
	
	   private JSONObject getJSONObject(InputStream inputStream) throws IOException, JSONException, ParseException{
	        BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
	        String line = "";
	        String sResult = "";
	        while((line = bufferedReader.readLine()) != null)
	            sResult += line;
	 
	        inputStream.close();
	        JSONObject result=(JSONObject) new JSONParser().parse(sResult);
	        return result;
	    }
	
	public void setIdSession(String idSession) {
		this.idSession = idSession;
	}
	
	public void setTextoCaptcha(String textoCaptcha) {
		this.textoCaptcha = textoCaptcha;
	}
	
	@Override
	public void validate() {
		if (this.pwd1==null || this.pwd2==null || this.pwd1.length()==0 || this.pwd2.length()==0) {
			super.addFieldError("pwd1", "Las passwords deben coincidir");
		}
		if (!this.pwd1.equals(this.pwd2)) {
			super.addFieldError("pwd2", "Las passwords deben coincidir");
		}
		if (this.email==null || this.email.length()==0) {
			super.addFieldError("email", "El email no puede estar vac??o");
		}
		if (this.email!=null && this.email.length()>45) {
			super.addFieldError("email", "El email no puede tener m??s de 45 caracteres");
		}
		if (!ValidatorUtil.validateEmail(email))
			super.addFieldError("email", "La direcci??n de email es inv??lida");
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public void setPwd1(String pwd1) {
		this.pwd1 = pwd1;
	}

	public void setPwd2(String pwd2) {
		this.pwd2 = pwd2;
	}

	public String getResultado() {
		if (exception!=null)
			return exception.toString();
		return "OK";
	}
}
